﻿using AutoMapper;
using MediatR;
using Sale.Api.Application.Command.Contract;
using Sale.Domain;
using Sale.ErrorCode;
using Sale.Infrastructure.Implement;

namespace Sale.Api.Application.Handler.Contract
{
    public class AddContractHandler : IRequestHandler<AddContractCommand, ApiResult<int>>
    {
        private readonly DatabaseContext db;
        private readonly ILogger<AddContractHandler> logger;
        private readonly IMapper mapper;

        public AddContractHandler(DatabaseContext db,ILogger<AddContractHandler> logger,IMapper mapper)
        {
            this.db = db;
            this.logger = logger;
            this.mapper = mapper;
        }
        public async Task<ApiResult<int>> Handle(AddContractCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> result=new ApiResult<int>();
            var contract=mapper.Map<ContractModel>(request);
            contract.ContractState = 0;
            contract.LoginUserId = 1;
            int r = await db.SqlSugar.Insertable(contract).ExecuteCommandAsync();
            if (r > 0)
            {
                result.Msg = "销售合同添加成功";
                result.Data = r;
                result.Code = ApiEnum.OK;
                logger.LogInformation(result.Msg);
            }
            else
            {
                result.Msg ="销售合同添加失败";
                result.Data = r;
                result.Code = ApiEnum.Fail;
                logger.LogError(result.Msg);
            }
            return await Task.FromResult(result);
        }
    }
}
